import datetime
from flask import Blueprint, render_template, request, session
from flask_login import login_required, current_user
from sqlalchemy import desc
from applications.common.curd import model_to_dicts, enable_status, disable_status, get_one_by_id
from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Member
from applications.models import Memberrole
from applications.models import User, AdminLog


admin_member = Blueprint('adminMember', __name__, url_prefix='/admin/member')


# 用户管理
@admin_member.get('/')
@authorize("admin:member:main")
def main():

    return render_template('admin/member/main.html')


# 表格数据
@admin_member.get('/data')
@authorize("admin:member:main")
def table():
    usernames = str_escape(request.args.get('userName', type=str))
    # print(role_name,"fffffffffffffffffffffffff")
    memberroleids = str_escape(request.args.get('memberroleid', type=int))
    enables = str_escape(request.args.get('enable', type=int))
    types = str_escape(request.args.get('type', type=int))
    filters = []
    if usernames:
        filters.append(Member.username.contains(usernames))
    if memberroleids:
        filters.append(Member.memberrole_id.contains(memberroleids))
    if enables:
        filters.append(Member.enable.contains(enables))
    if types:
        filters.append(Member.type.contains(types))
    member = Member.query.filter(*filters).layui_paginate()
    return table_api(
        data=[{
            'id': Member.id,
            'name': Member.name,
            'username': Member.username,
            'mailbox': Member.mailbox,
            'memberrole_id': Member.memberrole_id,
            'enable': Member.enable,
            'type': Member.type,
            'create_time': Member.create_time
        } for Member in member.items],
        count=member.total)

# 增加用户
@admin_member.get('/add')
@authorize("admin:member:add", log=True)
def add():

    return render_template('admin/member/add.html')


# 添加用户
@admin_member.post('/save')
@authorize("admin:member:add", log=True)
def save():
    req = request.get_json(force=True)
    memberroleid = req.get("memberroleid")
    roles= Memberrole.query.filter_by(id=memberroleid).first()
    name =roles.rolename
    enable = str_escape(req.get("enable"))
    mailbox = str_escape(req.get("mailbox"))
    password = str_escape(req.get("password"))
    remark = str_escape(req.get("remark"))
    username = str_escape(req.get("username"))
    sort = str_escape(req.get("sort"))
    create_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),

    if not memberroleid:
        return fail_api(msg="请选择角色组")
    if not username:
        return fail_api(msg="请填写用户名")
    if not password:
        return fail_api(msg="请输入密码")
    if not mailbox:
        return fail_api(msg="请输入邮箱")
    if bool(Member.query.filter_by(username=username).count()):
        return fail_api(msg="用户已经存在")
    # member = Member(name=name, username=username)
    member = Member(create_time=create_time,sort=sort,remark=remark,memberrole_id=memberroleid,enable=enable,mailbox=mailbox,name=name, username=username)
    member.set_password(password)

    db.session.add(member)
    db.session.commit()
    return success_api(msg="添加成功")

# 编辑
@admin_member.get('/edit/<int:id>')
@authorize("admin:member:edit", log=True)
def edit(id):
    r = get_one_by_id(model=Member, id=id)
    return render_template('admin/member/edit.html', member=r)


# 更新
# @admin_member.post('/update')
# @authorize("admin:member:edit", log=True)
# def update():
#     reqs = request.get_json(force=True)
#     id = reqs.get("memberId")
#     if not id:
#         return fail_api(msg="数据异常，请联系管理员")
#     memberroleid = reqs.get("memberroleid")
#     roles = Memberrole.query.filter_by(id=memberroleid).first()
#     name = roles.rolename
#     enable = str_escape(reqs.get("enable"))
#     mailbox = str_escape(reqs.get("mailbox"))
#     password = str_escape(reqs.get("password"))
#     remark = str_escape(reqs.get("remark"))
#     username = str_escape(reqs.get("username"))
#     sort = str_escape(reqs.get("sort"))
#     if not memberroleid:
#         return fail_api(msg="请选择角色组")
#     if not username:
#         return fail_api(msg="请填写用户名")
#     if not mailbox:
#         return fail_api(msg="请输入邮箱")
#     # if bool(Member.query.filter_by(username=username).count()):
#     #     return fail_api(msg="用户已经存在")
#     member = Member(sort=sort, remark=remark, memberrole_id=memberroleid, enable=enable, mailbox=mailbox, name=name,
#                     username=username)
#     if password:
#         member.set_password(password)
#     role = Memberrole.query.filter_by(id=id).update(member)
#     db.session.commit()
#     if not role:
#         return fail_api(msg="更新失败")
#     return success_api(msg="更新成功")


@admin_member.post('/update')
@authorize("admin:member:edit", log=True)
def update():
    reqs = request.get_json(force=True)
    id = reqs.get("memberId")
    if not id:
        return fail_api(msg="数据异常，请联系管理员")
    memberroleids  =  reqs.get("memberroleid")
    roles = Memberrole.query.filter_by(id=memberroleids).first()
    names = roles.rolename
    enables = str_escape(reqs.get("enable"))
    mailboxs = str_escape(reqs.get("mailbox"))
    remarks = str_escape(reqs.get("remark"))
    usernames = str_escape(reqs.get("username"))
    sorts = str_escape(reqs.get("sort"))
    if not memberroleids:
        return fail_api(msg="请选择角色组")
    if not usernames:
        return fail_api(msg="请填写用户名")
    if not mailboxs:
        return fail_api(msg="请输入邮箱")
    # if bool(Member.query.filter_by(username=usernames).count()):
    #     return fail_api(msg="用户已经存在")
    data = {
        "sort": sorts,
        "remark": remarks,
        "memberrole_id": memberroleids,
        "enable": enables,
        "mailbox": mailboxs,
        "name": names,
        "update_time":datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'username': usernames
    }
    role = Member.query.filter_by(id=id).update(data)
    db.session.commit()
    if not role:
        return fail_api(msg="更新失败")
    return success_api(msg="更新成功")

# 删除
@admin_member.delete('/remove/<int:id>')
@authorize("admin:member:remove", log=True)
def remove(id):
    member = Member.query.filter_by(id=id).first()
    # 删除该角色的权限和用户
    member.power = []
    member.user = []

    r = Member.query.filter_by(id=id).delete()
    db.session.commit()
    if not r:
        return fail_api(msg="角色删除失败")
    return success_api(msg="角色删除成功")


# 批量删除
@admin_member.delete('/batchRemove')
@authorize("admin:member:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        member = Member.query.filter_by(id=id).first()
        # 删除该角色的权限和用户
        member.power = []
        member.user = []

        r = Member.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")

# 启用
@admin_member.put('/enable')
@authorize("admin:member:edit", log=True)
def enable():
    id = request.get_json(force=True).get('Id')
    if id:
        res = enable_status(Member, id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="操作成功")
    return fail_api(msg="数据错误")


# 禁用
@admin_member.put('/disable')
@authorize("admin:member:edit", log=True)
def dis_enable():
    _id = request.get_json(force=True).get('Id')
    if _id:
        res = disable_status(Member, _id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="操作成功")
    return fail_api(msg="数据错误")




